var express = require('express');
var router = express.Router();
var util = require('util');
var fs = require('node-fs');
var EventProxy = require('eventproxy');
var path = require('path');
var xlsx = require('node-xlsx');

var resultJson = require('../result-json');
var User = require('../models/User');
var Course = require('../models/Course');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var setting = require('../setting');

router.post("/upload", function(req, res, next) {
	Utils.upload(req, function(json) {
		res.send(json);
	});
});

router.post("/uploadXLSX", function(req, res) {
	Utils.upload(req, function(json) {
		console.log(json.result)
		var filename = json.result.url;
		if (!filename)
			return res.send(resultJson(3));

		filename = setting.upload + filename;
		logger.debug("ready to parse:" + filename);

		try {
			var obj = xlsx.parse(filename);
			console.log(obj)
		} catch (error) {
			logger.log('error' + error)
			if (error)
				return res.send(resultJson(200));
		}
		var worksheet = obj[0];
		if (!worksheet)
			return res.send(resultJson(201));
		var excels = new Array();
		for (var i = 1; i < worksheet.data.length; i++) {
			excels[i - 1] = new Object;
			for (var j = 0; j < worksheet.data[0].length; j++) {
				if (worksheet.data[i][j])
					excels[i - 1][worksheet.data[0][j]] = (worksheet.data[i][j] + "").replace(/(^\s*)|(\s*$)/g, "");
			}
		};
		return res.send(resultJson(0, excels));
	});

})

router.get('/', function(req, res, next) {
	res.redirect('./admin/signup.html');
});

module.exports = router;